<template>
  <div class="m-hcity">
    <dl>
      <dt>最近访问：</dt>
      <dd v-for="item in newList" :key="item.id" @click="select(item)">
        {{ item.city === '市辖区' ? item.province : item.city }}
      </dd>
    </dl>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
import cookies from 'vue-cookies'
export default {
  data () {
    return {
      list: []
    }
  },
  computed: {
    // eslint-disable-next-line vue/return-in-computed-property
    newList () {
      if (this.list.length > 0) {
        return JSON.parse(window.localStorage.getItem('historyCollects')).slice(0, 9)
      } else {
        return []
      }
    }
  },
  mounted () {
    this.list = JSON.parse(window.localStorage.getItem('historyCollects')) || []
  },
  methods: {
    /* eslint-disable no-console */
    ...mapActions('geo', ['setPosition']),
    select (i) {
      console.log(i)
      const city = i.city === '市辖区' ? i.province : i.city
      // 移除cookies
      cookies.remove('city')
      // 获取local中的历史记录
      const historyCollects = JSON.parse(window.localStorage.getItem('historyCollects')) || []
      // 判断数据中是否已经有该城市
      const index = historyCollects.findIndex(item => item.city === city)
      console.log(index, historyCollects)
      if (index !== -1) {
        // 证明数据中有该城市
        historyCollects.splice(index, 1)
      }
      historyCollects.unshift({ province: i.province, city })
      console.log(i)
      this.setPosition({
        province: i.province,
        city
      })
      // 存储到cookies中
      cookies.set('city', city)
      // 存回local
      window.localStorage.setItem('historyCollects', JSON.stringify(historyCollects))
      location.href = '/'
    }
  }
}
</script>

<style lang="scss">
@import '@/assets/css/changeCity/hot.scss';
</style>
